package com.ting.mybatis.session;

import com.ting.mybatis.config.MyConfiguration;
import com.ting.mybatis.config.MyMapperStatement;
import com.ting.mybatis.executor.MyExecutor;
import com.ting.mybatis.proxy.MyMapperProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @Author: ting
 */
public class MySqlSession {

    private MyConfiguration myConfiguration;
    private MyExecutor myExecutor;

    public MySqlSession( MyConfiguration myConfiguration,MyExecutor myExecutor) {
        this.myExecutor = myExecutor;
        this.myConfiguration = myConfiguration;
    }

    MyMapperProxy myMapperProxy=new MyMapperProxy(this);

    //因为mapper可能有多种
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> interfaces){

        //返回mapper接口的代理对象
        return (T)Proxy.newProxyInstance(interfaces.getClassLoader(),new Class<?>[]{interfaces},
                myMapperProxy);
    }

    //查询一条数据
    public Object selectOne(String sqlId,Object parameter){

        MyMapperStatement myMapperStatement=myConfiguration.getMyMappedStatementMap().get(sqlId);
        //真正执行查询
        return myExecutor.query(myMapperStatement);

    }
}
